//
//  BBScanCusViewController.m
//  BaibuSeller
//
//  Created by X-MEN on 2021/7/19.
//  Copyright © 2021 BaiBu. All rights reserved.
//
#import "BBScanCusViewController.h"
#import <AVFoundation/AVFoundation.h>
//#import <ScanKitFrameWork/ScanKitFrameWork.h>

#define QRCodeWidth  260.0   //正方形二维码的边长
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height


#define STATUS_BAR_HEIGHT (iS_iPhoneX ? 44.f : 20.f)
// 导航栏高度
#define NAVIGATION_BAR_HEIGHT (iS_iPhoneX ? 88.f : 64.f)
// tabBar高度
#define TAB_BAR_HEIGHT (iS_iPhoneX ? (49.f + 34.f) : 49.f)
// home indicator
#define HOME_INDICATOR_HEIGHT (iS_iPhoneX ? 34.f : 0.f)


#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)
//#define iS_iPhoneX [BBDeviceTool isiPhoneX]
#define iS_iPhoneX \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX); })

@interface BBScanCusViewController ()<AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>
//输入输出的中间桥梁
@property(nonatomic, strong)  AVCaptureSession * session;

@property(strong, nonatomic) AVCaptureVideoPreviewLayer *layer;

@end

@implementation BBScanCusViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"扫描二维码";
    UIButton *photoAlbumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [photoAlbumBtn addTarget:self action:@selector(photoAlbumBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [photoAlbumBtn setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
    [photoAlbumBtn setTitle:@"相册" forState:UIControlStateNormal];
    photoAlbumBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    photoAlbumBtn.frame = CGRectMake(0, 44, 44, 44);
    //    searchBtn.backgroundColor = JZRandColor;
    UIBarButtonItem *photoAlbumBtnItem = [[UIBarButtonItem alloc] initWithCustomView:photoAlbumBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
    [nextBtn setTitle:@"继续" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    nextBtn.frame = CGRectMake(0, 0, 44, 44);
    //    searchBtn.backgroundColor = JZRandColor;
    UIBarButtonItem *nextBtnItem = [[UIBarButtonItem alloc] initWithCustomView:nextBtn];
    
    NSMutableArray *btnArray = [NSMutableArray array];
    [btnArray addObject:photoAlbumBtnItem];
    [btnArray addObject:nextBtnItem];
    
    self.navigationItem.rightBarButtonItems = btnArray;
    
    [self setupMaskView];//设置扫描区域之外的阴影视图 中间挖个洞
    
    [self setupScanWindowView];//设置扫描二维码区域的视图
    
    [self beginScanning];//开始扫二维码
    
}

- (void)setupMaskView {
    //设置统一的视图颜色和视图的透明度
    UIColor *color = [UIColor blackColor];
    float alpha = 0.7;
    
    //设置扫描区域外部上部的视图
    UIView *topView = [[UIView alloc]init];
    topView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, (SCREEN_HEIGHT-NAVIGATION_BAR_HEIGHT-QRCodeWidth)/2.0-NAVIGATION_BAR_HEIGHT);
    topView.backgroundColor = color;
    topView.alpha = alpha;
    
    //设置扫描区域外部左边的视图
    UIView *leftView = [[UIView alloc]init];
    leftView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT+topView.frame.size.height, (SCREEN_WIDTH-QRCodeWidth)/2.0,QRCodeWidth);
    leftView.backgroundColor = color;
    leftView.alpha = alpha;
    
    //设置扫描区域外部右边的视图
    UIView *rightView = [[UIView alloc]init];
    rightView.frame = CGRectMake((SCREEN_WIDTH-QRCodeWidth)/2.0+QRCodeWidth,NAVIGATION_BAR_HEIGHT+topView.frame.size.height, (SCREEN_WIDTH-QRCodeWidth)/2.0,QRCodeWidth);
    rightView.backgroundColor = color;
    rightView.alpha = alpha;
    
    //设置扫描区域外部底部的视图
    UIView *botView = [[UIView alloc]init];
    botView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT+QRCodeWidth+topView.frame.size.height,SCREEN_WIDTH,SCREEN_HEIGHT-NAVIGATION_BAR_HEIGHT-QRCodeWidth-topView.frame.size.height);
    botView.backgroundColor = color;
    botView.alpha = alpha;
    
    //将设置好的扫描二维码区域之外的视图添加到视图图层上
    [self.view addSubview:topView];
    [self.view addSubview:leftView];
    [self.view addSubview:rightView];
    [self.view addSubview:botView];
}

- (void)setupScanWindowView {
    
    //设置扫描区域的位置(考虑导航栏和电池条的高度为64)
    UIView *scanWindow = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-QRCodeWidth)/2.0,(SCREEN_HEIGHT-QRCodeWidth-NAVIGATION_BAR_HEIGHT)/2.0,QRCodeWidth,QRCodeWidth)];
    UIImageView *imagView = [[UIImageView alloc]initWithFrame:scanWindow.bounds];
    UIImage *image = [UIImage imageNamed:@"qrcode_border"];
    //拉伸图片
    image = [image stretchableImageWithLeftCapWidth:image.size.width *0.5 topCapHeight:image.size.width * 0.5];
    imagView.image = image;
    [scanWindow addSubview:imagView];
    scanWindow.clipsToBounds = YES;
    [self.view addSubview:scanWindow];
    
    //设置扫描区域的动画效果
    CGFloat scanNetImageViewH = 50;
    CGFloat scanNetImageViewW = scanWindow.frame.size.width;
    UIImageView *scanNetImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"qrcode_scanline_qrcode"]];
    scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
    CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
    scanNetAnimation.keyPath =@"transform.translation.y";
    scanNetAnimation.byValue = @(QRCodeWidth);
    scanNetAnimation.duration = 1.5;
    scanNetAnimation.repeatCount = MAXFLOAT;
    [scanNetImageView.layer addAnimation:scanNetAnimation forKey:nil];
    [scanWindow addSubview:scanNetImageView];
}

- (void)beginScanning {
    //初始化链接对象
    _session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) return;
    AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
    videoDataOutput.videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey: [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]};
    videoDataOutput.alwaysDiscardsLateVideoFrames = YES;
    //视频流输出代理
    [videoDataOutput setSampleBufferDelegate:self queue:dispatch_queue_create("scan.queue.video", NULL)];
    
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //特别注意的地方：有效的扫描区域，定位是以设置的右顶点为原点。屏幕宽所在的那条线为y轴，屏幕高所在的线为x轴
    CGFloat x = ((SCREEN_HEIGHT-QRCodeWidth-NAVIGATION_BAR_HEIGHT)/2.0)/SCREEN_HEIGHT;
    CGFloat y = ((SCREEN_WIDTH-QRCodeWidth)/2.0)/SCREEN_WIDTH;
    CGFloat width = QRCodeWidth/SCREEN_HEIGHT;
    CGFloat height = QRCodeWidth/SCREEN_WIDTH;
    output.rectOfInterest = CGRectMake(x, y, width, height);
    
    //设置代理在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [_session addInput:input];
    [_session addOutput:output];
    if ([_session canAddOutput:videoDataOutput]) {
        [_session addOutput:videoDataOutput];
    }
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    self.layer = layer;
    //开始捕获
    [_session startRunning];
    
}


-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    //    if (metadataObjects.count>0) {
    //
    //        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0];
    //        // 停止扫描
    //        [self.session stopRunning];
    //
    //        // 将预览图层移除
    //        [self.layer removeFromSuperlayer];
    //        //输出扫描字符串
    //        NSLog(@"%@",metadataObject.stringValue);
    //
    //
    //           } else {
    //
    //        NSLog(@"没有扫描到数据");
    //    }
}

- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
//    NSDictionary *resultDic = [HmsBitMap bitMapForSampleBuffer:sampleBuffer withOptions:[[HmsScanOptions alloc] initWithScanFormatType:ALL Photo:false]];
//    if (resultDic != nil) {
//        NSString *result = resultDic[@"text"];
//        if (result.length > 0) {
//            // 停止扫描
//            [self.session stopRunning];
//            NSLog(@"result=====%@", result);
//        }
//    }
}

- (void)photoAlbumBtnClick {
    [self showImagePickerController];
}

- (void)nextBtnClick {
    // 继续扫描
    [self.session startRunning];
}

- (void)showImagePickerController {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    //        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    //        picker.mediaTypes = mediaTypes;
    //        picker.allowsEditing = YES;
    //    }
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.modalPresentationStyle = UIModalPresentationOverFullScreen;
    picker.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//    NSDictionary *resultDic = [HmsBitMap bitMapForImage:image withOptions:[[HmsScanOptions alloc] initWithScanFormatType:ALL Photo:true]];
//    NSLog(@"resultDic=====%@", resultDic);
    [picker dismissViewControllerAnimated:YES completion:^{ }];
}

@end
